# Author: zhuxuanlin
# Email: xuanlinzhu@qq.com
# Date: 2024-4-3
# Version: 1.1

# Description: This file is used to create a quick template project for CMake.

import os


def parse_config_file_cmake(config_file):
    config_vars = {}
    with open(config_file, 'r') as f:
        for line in f:
            # Skip comments and empty lines
            if line.startswith('#') or line.strip() == '':
                continue
            # Parse configuration line
            key, value = line.strip().split('=', 1)
            # Remove 'CONFIG_' prefix from the key name
            key = key[7:] if key.startswith('CONFIG_') else key
            # Handle quotes in the value
            if value.startswith('"') and value.endswith('"'):
                value = value[1:-1]
            # Add to dictionary
            config_vars[key] = value
    return config_vars


def write_cmake_file(config_vars, cmake_file):
    with open(cmake_file, 'w') as f:
        f.write('# Automatically generated by config_to_cmake.py\n')
        for key, value in config_vars.items():
            f.write('set({} "{}")\n'.format(key, value))


def convert_config_to_cmake(config_file, cmake_file):
    config_vars = parse_config_file_cmake(config_file)
    write_cmake_file(config_vars, cmake_file)


def parse_config_file_header(config_file):
    config_vars = []
    with open(config_file, 'r') as f:
        for line in f:
            # Skip comments and empty lines
            if line.startswith('#') or line.strip() == '':
                continue
            # Parse configuration line
            key, value = line.strip().split('=', 1)
            # If the value is 'y', replace it with a space
            value = value.strip()
            if value == 'y':
                value = '1'
            # Remove 'CONFIG_' prefix from the key name
            key = key[7:] if key.startswith('CONFIG_') else key
            # Add to list
            config_vars.append((key, value))
    return config_vars


def write_config_header(config_vars, header_file):
    with open(header_file, 'w') as f:
        f.write('// Automatically generated by config_to_header.py\n')
        f.write('#ifndef __CK_CONFIG_H__\n')
        f.write('#define __CK_CONFIG_H__\n\n')

        for key, value in config_vars:
            f.write('#define {} {}\n'.format(key, value))

        f.write('\n#endif // __CK_CONFIG_H__')


def convert_config_to_header(config_file, header_file):
    config_vars = parse_config_file_header(config_file)
    write_config_header(config_vars, header_file)


config_file = '.config'       # Path to your .config file
cmake_file = 'ck_config.cmake'  # Path to the generated config.cmake file
header_file = 'ck_config.h'     # Path to the generated ck_config.h file

# Convert .config file to config.cmake file
convert_config_to_cmake(config_file, cmake_file)

# Convert .config file to ck_config.h file
convert_config_to_header(config_file, header_file)